package com.panda.utils;


import com.panda.command.Console;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

//提取出来函数的调用以及函数的声明
class FunctionUtils {

     /*

        如果需要把函数声明进$scope中,需要使用 scope function 来声明一个函数

      */

    private static final Pattern pattern = Pattern.compile("(?<!=)[\n ]*(scope|global) +function[\n ]+([a-zA-Z_][a-zA-Z0-9_]*)[\n ]*\\(");

    static String transform(String s) {
        return scope(s);
    }

    private static final Pattern param = Pattern.compile("function[\n ]*([\n ]+[a-zA-Z_][a-zA-Z0-9_]*)?[\n ]*(?=\\()");


    private static String param(String s) {

        Matcher matcher = param.matcher(s);

        String r = s;

        while (matcher.find()) {


            int pe = Finder.findParam(s.toCharArray(), matcher.end());

            //参数
            if (pe == -1) {
                Console.warning("存在函数声明没有形参:" + s);
                continue;
            }

            String p = s.substring(matcher.end(), pe).trim();

            p = p.substring(1, p.length() - 1).trim();

            //没有形参直接跳过
            if (p.equals("")) {
                continue;
            }

            //形参
            String[] ps = p.split(",");

            int be = Finder.findBody(s.toCharArray(), pe);

            if (be == -1) {
                Console.warning("存在函数声明没有函数体:" + s);
                continue;
            }

            //需要被替换的函数体
            String fc = s.substring(matcher.start(), be);

            String tf = fc;

            //形参也会被改变
            for (String pp : ps) {

                pp = pp.trim();

                if (pp.startsWith("$scope.")) {
                    tf = tf.replace(pp, pp.replaceFirst("\\$scope.", ""));

                } else if (pp.startsWith("$rootScope.")) {
                    tf = tf.replace(pp, pp.replaceFirst("\\$rootScope.", ""));
                }

            }

            //替换掉函数
            r = r.replace(fc, tf);


        }


        return r;
    }


    private static String scope(String s) {

        Matcher matcher = pattern.matcher(s);

        while (matcher.find()) {


            String ky = matcher.group(1);

            //函数名
            String name = matcher.group(2);

            //将其改变成变量声明的形式.即 scope/global [函数名] =function(....

            String toString = "\n\n " + ky + " " + name + " = function(";

            s = s.replace(matcher.group(), toString);

        }

        return s;

    }

    /*
        将$scope 和$rootScope进行反向还原
     */
    static String protectParam(String s) {
        return param(s);
    }



}
